//
//  UserCountViewModel.swift
//  Weibo
//
//  Created by mac on 16/1/13.
//  Copyright © 2016年 mac. All rights reserved.
//

import UIKit
import AFNetworking
import SVProgressHUD

class UserCountViewModel: NSObject {
    
    var userAccount: OAuthLoginModel?
    
    var userLoginFlag: Bool {
        return userAccount?.access_token != nil
    }
    
    var userName: String {
        
        return (userAccount?.name ?? "")
    }
    
    var access_token: String {
        return (userAccount?.access_token)!
    }
    
    var uid: String {
        return (userAccount?.uid)!
    }
    
    var headerImageURL: NSURL {
        return NSURL(string: userAccount?.avatar_large ?? "")!
    }
    
   override init() {
        userAccount = OAuthLoginModel.loadUserInfo()
    
        super.init()
    }
    
    
    func loadUserTokenWithCode(code: String, finished: (flag: Bool) -> ()) {
        
        let parameters = ["client_id":client_id,"client_secret":client_secret,"grant_type":grant_type,"code":code,"redirect_uri":redirect_uri]
        
        let manaeger: MKNetworkTools = MKNetworkTools.shareNetworking
        manaeger.responseSerializer.acceptableContentTypes?.insert("text/plain")
        
        manaeger.POST("oauth2/access_token", parameters: parameters, progress: nil, success: { (task, responseData) -> Void in
            
            guard let dict: [String:AnyObject] = responseData as? [String:AnyObject] else {
                print("格式错误")
                finished(flag: false)
                return
            }
            
            let model: OAuthLoginModel = OAuthLoginModel(dict: dict)
            self.loadUserInfo(model,finished: finished)
            
            }) { (task, error) -> Void in
                SVProgressHUD.showErrorWithStatus("网络连接错误...")
        }
    }
    
    private func loadUserInfo(model: OAuthLoginModel, finished: (flag: Bool) -> ()) {
        let manaeger: MKNetworkTools = MKNetworkTools.shareNetworking
        manaeger.GET("/2/users/show.json?access_token="+model.access_token!+"&uid="+model.uid!, parameters: nil, progress: nil, success: { (task, responseObject) -> Void in
            
            guard let dic: [String:AnyObject] = responseObject as? [String:AnyObject] else {
                
                print("格式错误..")
                
                finished(flag: false)
                return
            }
            model.name = dic["name"] as? String
            model.avatar_large = dic["avatar_large"] as? String
            //归档
            model.saveUserInfo()
            finished(flag: true)
            
            }){ (task, error) -> Void in
                finished(flag: false)
        }
    }
}
